//
//  EDSAppDelegateTool.m
//  DriveSchoolCoach
//
//  Created by TangBin on 2019/7/5.
//  Copyright © 2019 TangBin. All rights reserved.
//

#import "EDSAppDelegateTool.h"
#import "TYZNavRootVCInfo.h"
#import "TYZNetworkConfig.h"
#import "TYZBaseViewController.h"
#import "EDSMoLocationManager.h"
//#import <LeanCloudObjc/Foundation.h>
#import "ZTDBManager.h"
#import "WXApi.h"
#import "TYZLogManager.h"
#import "WDLocationManager.h" // 定位


@interface EDSAppDelegateTool () <UITabBarControllerDelegate, WXApiDelegate, AMapLocationManagerDelegate>
@property (nonatomic, assign) BOOL isFirst; ///< 用户安装app不是第一次打开
@property (nonatomic, assign) EDS_NETWORK_STATUS networkStatus; ///< 网络状态

/// 点击tabBarItem的时间
@property (nonatomic, strong) NSDate *lastDate;

/// 随机数
@property (nonatomic, assign) NSInteger randomNumber;

@property (nonatomic, strong) AMapLocationManager *locationManager;

@end

@implementation EDSAppDelegateTool

+ (instancetype)sharedInstance
{
    static EDSAppDelegateTool *instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[[self class] alloc] init];
    });
    return instance;
}

- (instancetype)init
{
    if (self = [super init])
    {
        [self setup];
    }
    return self;
}

- (void)setup
{
    [self setupUUID];
    // 网络监听
    [self monitorReachabilityStatus];
    id first = [EDSUtility objectForKey:@"isFirst"];
    if (!first)
    {// 这里有可能是用户曾经使用过app，删除了，后来有安装了。
        [TYZKeychain remove:kUserInfo];
        self.isFirst = NO;
        [EDSUtility setObject:@(self.isFirst) forKey:@"isFirst"];
    }
    else
    {
        self.isFirst = [first boolValue]; // 不是第一次打开
    }
    // 设置网络请求的根地址
    [TYZNetworkConfig sharedConfig].baseUrl = kBaseUrl;
    // 用户信息
    id userInfoModel = [TYZKeychain load:kUserInfo];
    if (userInfoModel)
    {
        self.userInfoModel = userInfoModel;
    }
    
    NSArray *routes = [EDSUtility readCacheDataLocalKey:kCacheUserRoutesData saveFilename:kCacheUserRoutesFileName];
    if (routes) {
        self.userRoutes = routes;
    } else {
        self.userRoutes = @[];
    }
    
    [self setSvProgressHUD];
//    [self registerAPNS];
    // 百度初始化
//    [self setupBaidu];
    
    // 高德初始化
    [self setupGaode];
    
    //友盟
    [self setupUM];
    // 微信初始化
    [self setupWXApi];
//    [self setupBugly];
    
    // 初始化定位
    [[WDLocationManager shareInstance] configLocationManager];
    
    [self setNavBarAppearence];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appWillEnterForeground:) name:UIApplicationWillEnterForegroundNotification object:nil];
    // 监听重新返回APP
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onAppWillResignAction) name:UIApplicationWillResignActiveNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onAppBecomeActive) name:UIApplicationDidBecomeActiveNotification object:nil];
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        // 网络状态监控
        [self setupNetworkStatusChange];
        
//        [self requestWithAlarmRule];
        
        // 获取参数
        [self requestWithTaskParameters];
        
        [self requestWithUserRoutes:nil];
    });
}

#pragma mark 高德初始化
- (void)setupGaode
{
    [self setGaode:GDKey];
//    self.genViewModel = [[GeneralViewModel alloc]init];
//    [self.genViewModel requestMapAccountCompletion:^(EDSRespondDataEntity * _Nonnull respond) {
//        if(respond.code == EDS_NETWORK_SUCCESS){
//            NSString *key = respond.data;
//            [self setGaode:key];
//        }else{
//            [self setGaode:GDKey];
//        }
//    }];
}
-(void)setGaode:(NSString *)key
{
    [AMapServices sharedServices].apiKey = key;
    [AMapServices sharedServices].enableHTTPS = YES;
    [MAMapView updatePrivacyShow:AMapPrivacyShowStatusDidShow privacyInfo:AMapPrivacyInfoStatusDidContain];
    [MAMapView updatePrivacyAgree:AMapPrivacyAgreeStatusDidAgree];
    self.locationManager = [[AMapLocationManager alloc] init];
    self.locationManager.delegate = self;
    self.locationManager.locationTimeout = 2;
    self.locationManager.reGeocodeTimeout = 2;
    [self.locationManager setDesiredAccuracy:kCLLocationAccuracyHundredMeters];
    @weakify(self);
    [self.locationManager requestLocationWithReGeocode:YES completionBlock:^(CLLocation *location, AMapLocationReGeocode *regeocode, NSError *error) {
        @strongify(self);
        if (error)
        {
            if (error.code == AMapLocationErrorLocateFailed)
            {
//                self.city = @"合肥市";
//                self.latitude = 31.86694;
//                self.longitude = 117.2827;
                return;
            }
        }
        if (regeocode) {
            self.city = regeocode.city;
            self.address = [NSString stringWithFormat:@"%@%@",regeocode.province,regeocode.city];
            self.latitude = location.coordinate.latitude;
            self.longitude = location.coordinate.longitude;
            
            // 临时加上
//            [AppContext getInstance].city = @"合肥市";
//            [AppContext getInstance].lat = 31.86694;
//            [AppContext getInstance].lon = 117.2827;
        } else {
//            self.city = @"合肥市";
//            self.latitude = 31.86694;
//            self.longitude = 117.2827;
        }
    }];
}

/// 微信初始化
- (void)setupWXApi
{
    if (![WXApi isWXAppInstalled])
    {
        return;
    }
    BOOL ret = [WXApi registerApp:kWEIXIN_APP_ID universalLink:kWEIXIN_APP_UNIVERSAL_LINK];
    if (ret)
    {
        debugLog(@"微信sdk初始化成功");
    }
    /*
     WXULCheckStepParams,
     WXULCheckStepSystemVersion,
     WXULCheckStepWechatVersion,
     WXULCheckStepSDKInnerOperation,
     WXULCheckStepLaunchWechat,
     WXULCheckStepBackToCurrentApp, --- 5
     WXULCheckStepFinal,
     */
//    [WXApi checkUniversalLinkReady:^(WXULCheckStep step, WXCheckULStepResult * _Nonnull result) {
//
//        NSString *log = [NSString stringWithFormat:@"微信测试函数：%@, state=%u, errorInfo=%@, 修正建议=%@", @(step), result.success, result.errorInfo, result.suggestion];
//        debugLog(@"%@", log);
////        [[TYZLogManager sharedInstance] logInfo:@"" logStr:log, nil];
//    }];
}

/**
 唯一标识码
 */
- (NSString *)setupUUID
{
    NSString *bundleId = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleIdentifier"];
    NSString *uuid = [TYZKeychain load:bundleId];
    if ([objectNull(uuid) isEqualToString:@""])
    {
        uuid = [NSString stringWithUUID];
        [TYZKeychain save:bundleId data:uuid];
    }
    return uuid;
}

- (NSString *)deviceId
{
    return [self setupUUID];
}

- (void)setNavBarAppearence
{
    // 设置是 广泛使用WRNavigationBar，还是局部使用WRNavigationBar，目前默认是广泛使用
//    [WRNavigationBar wr_widely];
    //    [WRNavigationBar wr_setBlacklist:@[@"SpecialController",
    //                                       @"TZPhotoPickerController",
    //                                       @"TZGifPhotoPreviewController",
    //                                       @"TZAlbumPickerController",
    //                                       @"TZPhotoPreviewController",
    //                                       @"TZVideoPlayerController"]];
    
    // 设置导航栏默认的背景颜色
//    [WRNavigationBar wr_setDefaultNavBarBarTintColor:kNavBarBackgroundColor];
    // 设置导航栏所有按钮的默认颜色
//    [WRNavigationBar wr_setDefaultNavBarTintColor:[UIColor whiteColor]];
    // 设置导航栏标题默认颜色
//    [WRNavigationBar wr_setDefaultNavBarTitleColor:[UIColor whiteColor]];
    // 统一设置状态栏样式
//    [WRNavigationBar wr_setDefaultStatusBarStyle:UIStatusBarStyleLightContent];
    
    // 如果需要设置导航栏底部分割线隐藏，可以在这里统一设置
//    [WRNavigationBar wr_setDefaultNavBarShadowImageHidden:YES];
}

//注册推送 //推送的形式：标记，声音，提示
-(void)registerAPNS
{
    /*
    if (TARGET_IPHONE_SIMULATOR)
    {
        return;
    }
    
    // 注册推送
    if (@available(iOS 10.0, *))
    {
        // iOS10及以上注册远程通知的方法
        UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
        // 必须写代理，不然无法监听通知的接收与点击
        center.delegate = self;
        [center requestAuthorizationWithOptions:UNAuthorizationOptionAlert | UNAuthorizationOptionBadge | UNAuthorizationOptionSound completionHandler:^(BOOL granted, NSError * _Nullable error) {
            if (granted) {
                // 点击允许
                debugLog(@"注册成功");
                
                [center getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {
                    debugLog(@"settings=%@", settings);
                }];
            } else {
                // 点击不允许
                debugLog(@"注册失败");
                
            }
        }];
        [[UIApplication sharedApplication] registerForRemoteNotifications];
    }
    else if (@available(iOS 8.0, *)) {
        // iOS8-iOS10注册远程通知的方法
        UIUserNotificationType types = UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound;
        UIUserNotificationSettings *mySettings = [UIUserNotificationSettings settingsForTypes:types categories:nil];
        [[UIApplication sharedApplication] registerUserNotificationSettings:mySettings];
        [[UIApplication sharedApplication] registerForRemoteNotifications];
    } else {
        // 在iOS8之前注册远程通知的方法，如果项目中要支持iOS8之前的版本，必须要写此方法
        UIRemoteNotificationType types = UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound;
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:types];
    }
    
//    [UNUserNotificationCenter requestAuthorizationWithOptions:completionHandler:] and -[UNUserNotificationCenter setNotificationCategories:]
    
//    //        NSLog(@"tb--注册推送");
//    [[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings
//                                                                         settingsForTypes:(UIUserNotificationTypeSound |
//                                                                                           UIUserNotificationTypeAlert |
//                                                                                           UIUserNotificationTypeBadge)
//                                                                         categories:nil]];
//    [[UIApplication sharedApplication] registerForRemoteNotifications];
     */
}

/**
 百度初始化
 */
- (void)setupBaidu
{
    
}

/**
 初始友盟
 */
- (void)setupUM
{
    
    //友盟
    [UMConfigure initWithAppkey:kUM_STATISTICAL_KEY_ID channel:@"App Store"];
#ifdef DEBUG
//    [[UMSocialManager defaultManager] openLog:YES];
#else
#endif
}

- (void)setupBugly
{
//    BuglyConfig *config = [[BuglyConfig alloc] init];
//    config.debugMode = YES;
//    [Bugly startWithAppId:@"6d3ce83b38" config:config];
}
/// 网络状态改变
- (void)setupNetworkStatusChange
{
    
}

/**
 登录视图控制器初始化
 */
- (void)setupLoginVC
{
    // 登录页面
    if (!_loginNav)
    {
        TYZNavInfo *navInfo = [[TYZNavInfo alloc] initWithNavBackgroundColor:kNavBarBackgroundColor titleFont:kNavBarTitleFont titleColor:kNavBarTitleColor];
        UIViewController *loginVC =nil;
        loginVC = [[TYZRouter sharedInstance] getLoginVC:nil];
        _loginNav = [[TYZBaseNavigationController alloc] initWithRootViewController:loginVC];
        [_loginNav setupNavCommonInfo:navInfo];
    }
}

/**
 主控制器初始化
 */
- (void)setupMainVC
{
    if (!_rootTabBar)
    {
        NSMutableArray *addList = [NSMutableArray new];
        // 到站服务
        if ([self hasArrivalService]) {
            TYZNavRootVCInfo *arrivalServiceInfo = [[TYZNavRootVCInfo alloc] initWithInfo:@"到站服务" clsName:nil imgNorName:@"ic_tab_main_nor" imgSelName:@"ic_tab_main_sel"];
            arrivalServiceInfo.vc = [[TYZRouter sharedInstance] getRootArrivalServiceVC:nil];
            [addList addObject:arrivalServiceInfo];
        }
        
        // 外出救援
        if ([self hasOutRescue]) {
            TYZNavRootVCInfo *goutRescueInfo = [[TYZNavRootVCInfo alloc] initWithInfo:@"外出救援" clsName:nil imgNorName:@"ic_tab_rescue_nor" imgSelName:@"ic_tab_rescue_sel"];
            goutRescueInfo.vc = [[TYZRouter sharedInstance] getRootGoutRescueVC:nil];
            [addList addObject:goutRescueInfo];
        }
        
        // 扫码
//        TYZNavRootVCInfo *scanCodesInfo = [[TYZNavRootVCInfo alloc] initWithInfo:@"扫码" clsName:nil imgNorName:@"ic_tab_main_nor" imgSelName:@"ic_tab_main_sel"];
//        scanCodesInfo.vc = [[TYZRouter sharedInstance] getRootScanCodesVC:nil];

        // 工单
        if ([self hasWorkOrder]) {
            TYZNavRootVCInfo *workOrderInfo = [[TYZNavRootVCInfo alloc] initWithInfo:@"工单" clsName:nil imgNorName:@"ic_tab_order_nor" imgSelName:@"ic_tab_order_sel"];
            workOrderInfo.vc = [[TYZRouter sharedInstance] getRootWorkOrderVC:nil];
            [addList addObject:workOrderInfo];
        }
        
        // 我的
        if ([self hasMine]) {
            TYZNavRootVCInfo *mineInfo = [[TYZNavRootVCInfo alloc] initWithInfo:@"我的" clsName:nil imgNorName:@"ic_tab_mine_nor" imgSelName:@"ic_tab_mine_sel"];
            mineInfo.vc = [[TYZRouter sharedInstance] getRootMineVC:nil];
            [addList addObject:mineInfo];
        }
        
        
        _rootTabBar = [[TYZCustomTabBarController alloc] initWithShowMiddleBtn:NO midNorImgName:nil midSelImgName:nil];
        _rootTabBar.delegate = self;
        NSArray *vcs = [addList copy];
        
        TYZNavInfo *navInfo = [[TYZNavInfo alloc] initWithNavBackgroundColor:kNavBarBackgroundColor titleFont:kNavBarTitleFont titleColor:kNavBarTitleColor];
        
        [_rootTabBar setupChildViewController:vcs navInfo:navInfo];
        [_rootTabBar setupTabBarItemTextAttributes:kTabBarItemTitleNorColor selTitleColor:kTabBarItemTitleSelColor titleFont:kTabBarItemTitleFont];
    }
    else
    {
        self.rootTabBar.selectedIndex = 0;
    }
}

/// 登录
- (void)presentLogin
{
    if (self.loginNav)
    {
        self.loginNav = nil;
    }
    [self setupLoginVC];
    [TYZJumpVCManager presentBaseVC:self.window.rootViewController presentVC:_loginNav completion:nil];
}

- (void)updateRootVC
{
    if (self.userInfoModel.loginState == 1)
    {// 已经登录
        [self setupMainVC];
        self.window.rootViewController = _rootTabBar;
    }
    else
    {// 没有登录
        self.rootTabBar = nil;
        [self setupLoginVC];
        self.window.rootViewController = _loginNav;
//        [TYZJumpVCManager presentBaseVC:self.window.rootViewController presentVC:_loginNav completion:nil];
    }
    
    
    /*
    [self setupMainVC];
    _rootTabBar.selectedIndex = 0;
    self.window.rootViewController = _rootTabBar;
     */
    
//    debugLog(@"currname=%@", [[XJRingLetterManager shareInstance] currentUsername]);
    
    /*
    [[XJRingLetterManager shareInstance] logout:^(EMError * _Nonnull error) {
        debugLog(@"error=%@", error);
        debugLog(@"dd");
    }];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [[XJRingLetterManager shareInstance] loginWithUserName:@"1000" password:@"@fansyun.cn:12345" completion:^(NSString * _Nonnull aUsername, EMError * _Nonnull aError) {
            debugLog(@"ausername=%@", aUsername);
        }];
    });*/
}

/// 判断是否登录
/// @param vc vc description
- (BOOL)isLogin:(UIViewController *)vc
{
//    if (!self.userInfoModel || self.userInfoModel.loginState == 0) {
//        UIViewController *loginvC = [[TYZRouter sharedInstance] getLoginVC:nil];
//        [TYZJumpVCManager pushBaseVC:vc pushVC:loginvC];
//        return NO;
//    }
    return YES;
}

/**
 进入前台的通知
 
 @param noti noti description
 */
- (void)appWillEnterForeground:(NSNotification *)noti
{
//    [SVProgressHUD showInfoWithStatus:@"进入前台的通知"];
}

- (void)onAppWillResignAction
{
//    [SVProgressHUD showInfoWithStatus:@"onAppWillResignAction"];
}

- (void)onAppBecomeActive
{
//    [SVProgressHUD showInfoWithStatus:@"onAppBecomeActive"];
}


#pragma mark - 网络监听
/**
 监听网络状态的方法
 */
- (void)monitorReachabilityStatus
{
    @weakify(self);
    // 开始监听
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    
    // 网络状态改变回调
    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        @strongify(self);
        switch (status)
        {
            case AFNetworkReachabilityStatusReachableViaWWAN:
            {
//                debugLog(@"蜂窝网络");
                self.networkStatus = EDS_NETWORK_STATUS_WWAN;
            }break;
            case AFNetworkReachabilityStatusReachableViaWiFi:
            {
//                debugLog(@"WIFI");
                self.networkStatus = EDS_NETWORK_STATUS_WIFI;
            } break;
            case AFNetworkReachabilityStatusNotReachable:
            {
//                debugLog(@"没有网络");
                self.networkStatus = EDS_NETWORK_STATUS_NOT;
            } break;
            default:
            {
//                debugLog(@"未知");
                self.networkStatus = EDS_NETWORK_STATUS_NOT;
            } break;
        }
    }];
}




- (void)setSvProgressHUD
{
    [SVProgressHUD setDefaultStyle:SVProgressHUDStyleDark];
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeClear];
    [SVProgressHUD setDefaultAnimationType:SVProgressHUDAnimationTypeFlat];
    [SVProgressHUD setMinimumDismissTimeInterval:1.5];
}

- (BOOL)application:(UIApplication *)application continueUserActivity:(NSUserActivity *)userActivity restorationHandler:(void (^)(NSArray<id<UIUserActivityRestoring>> * _Nullable))restorationHandler
{
    return [WXApi handleOpenUniversalLink:userActivity delegate:self];
}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    NSString *urlStr = url.absoluteString;
    // 微信
    if ([urlStr hasPrefix:kWEIXIN_APP_ID])
    {
        return [WXApi handleOpenURL:url delegate:self];
    }
    
    if (url)
    {
        // 从路径中获取完整的文件名(带后缀)
        NSString *fileName = url.lastPathComponent;
        // path 类似这种格式 file:///private/var/mobile/Containers/Data/Application/163890FF-2C20-4024-A56E-70CB0AC9964B/Documents/Inbox/%E4%B8%AD%E5%AF%B0%E5%AE%89%E5%BE%BD%E5%88%86%E5%85%AC%E5%8F%B8%E6%9C%88%E5%BA%A6%E7%BB%A9%E6%95%88%E8%80%83%E6%A0%B8%E8%A1%A8_2019.11_%E5%94%90%E6%96%8C-7.xlsx
        NSString *path = url.absoluteString; // 完成的url字符串
        path = [self URLDecodedString:path]; // 解决url编码问题
        NSMutableString *string = [[NSMutableString alloc] initWithString:path];
        if ([path hasPrefix:@"file://"]) // 通过前缀来判断是文件
        {
            NSString *ext = [[path pathExtension] lowercaseString]; // 扩展名
            debugLog(@"文件扩展名=%@", ext);
            if ([ext isEqualToString:@"xlsx"] || [ext isEqualToString:@"xls"] || [ext isEqualToString:@"docx"] || [ext isEqualToString:@"doc"])
            {
                [string replaceOccurrencesOfString:@"file://" withString:@"" options:NSCaseInsensitiveSearch range:NSMakeRange(0, path.length)];
                // 此时获取到文件存储在本地的路径，就可以在自己需要使用的页面使用了
                NSDictionary *dict = @{@"fileName":fileName, @"filePath":objectNull(string), @"extension": objectNull(ext)};
//                [[TYZLogManager sharedInstance] logInfo:@"" logStr:@"收到外部文件，发送通知", nil];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"kFROM_EXTERNAL_REVC_FILE_NOTI" object:nil userInfo:dict];
                });
            }
            
            return YES;
        }
    }
//    BOOL result = [[UMSocialManager defaultManager] handleOpenURL:url];
//    if (!result)
//    {
//        // 其他如支付等SDK的回调
//    }
    return YES;
    
    //6.3的新的API调用，是为了兼容国外平台(例如:新版facebookSDK,VK等)的调用[如果用6.2的api调用会没有回调],对国内平台没有影响
//    BOOL result = [[UMSocialManager defaultManager]  handleOpenURL:url options:options];
//    if (!result)
//    {
//        // 其他如支付等SDK的回调
//    }
    return YES;
}

- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey, id> *)options
{
    NSString *urlStr = url.absoluteString;
    debugLog(@"openUrl=%@", urlStr);
    if ([urlStr hasPrefix:kWEIXIN_APP_ID])
    {
        return [WXApi handleOpenURL:url delegate:self];
    }
    
    if (url)
    {
        // 从路径中获取完整的文件名(带后缀)
        NSString *fileName = url.lastPathComponent;
        // path 类似这种格式 file:///private/var/mobile/Containers/Data/Application/163890FF-2C20-4024-A56E-70CB0AC9964B/Documents/Inbox/%E4%B8%AD%E5%AF%B0%E5%AE%89%E5%BE%BD%E5%88%86%E5%85%AC%E5%8F%B8%E6%9C%88%E5%BA%A6%E7%BB%A9%E6%95%88%E8%80%83%E6%A0%B8%E8%A1%A8_2019.11_%E5%94%90%E6%96%8C-7.xlsx
        NSString *path = url.absoluteString; // 完成的url字符串
        path = [self URLDecodedString:path]; // 解决url编码问题
        NSMutableString *string = [[NSMutableString alloc] initWithString:path];
        if ([path hasPrefix:@"file://"]) // 通过前缀来判断是文件
        {
            NSString *ext = [[path pathExtension] lowercaseString]; // 扩展名
            debugLog(@"文件扩展名=%@", ext);
            if ([ext isEqualToString:@"xlsx"] || [ext isEqualToString:@"xls"] || [ext isEqualToString:@"docx"] || [ext isEqualToString:@"doc"])
            {
                [string replaceOccurrencesOfString:@"file://" withString:@"" options:NSCaseInsensitiveSearch range:NSMakeRange(0, path.length)];
                // 此时获取到文件存储在本地的路径，就可以在自己需要使用的页面使用了
                NSDictionary *dict = @{@"fileName":fileName, @"filePath":objectNull(string), @"extension": objectNull(ext)};
//                [[TYZLogManager sharedInstance] logInfo:@"" logStr:@"收到外部文件，发送通知", nil];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"kFROM_EXTERNAL_REVC_FILE_NOTI" object:nil userInfo:dict];
                });
            }
            
            return YES;
        }
    }
//    BOOL result = [[UMSocialManager defaultManager] handleOpenURL:url];
//    if (!result)
//    {
//        // 其他如支付等SDK的回调
//    }
    return YES;
    
    //6.3的新的API调用，是为了兼容国外平台(例如:新版facebookSDK,VK等)的调用[如果用6.2的api调用会没有回调],对国内平台没有影响
//    BOOL result = [[UMSocialManager defaultManager]  handleOpenURL:url options:options];
//    if (!result)
//    {
//        // 其他如支付等SDK的回调
//    }
    return YES;
}

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
    if (url)
    {
        // 从路径中获取完整的文件名(带后缀)
        NSString *fileName = url.lastPathComponent;
        // path 类似这种格式 file:///private/var/mobile/Containers/Data/Application/163890FF-2C20-4024-A56E-70CB0AC9964B/Documents/Inbox/%E4%B8%AD%E5%AF%B0%E5%AE%89%E5%BE%BD%E5%88%86%E5%85%AC%E5%8F%B8%E6%9C%88%E5%BA%A6%E7%BB%A9%E6%95%88%E8%80%83%E6%A0%B8%E8%A1%A8_2019.11_%E5%94%90%E6%96%8C-7.xlsx
        NSString *path = url.absoluteString; // 完成的url字符串
        path = [self URLDecodedString:path]; // 解决url编码问题
        NSMutableString *string = [[NSMutableString alloc] initWithString:path];
        if ([path hasPrefix:@"file://"]) // 通过前缀来判断是文件
        {
            NSString *ext = [[path pathExtension] lowercaseString]; // 扩展名
            debugLog(@"文件扩展名=%@", ext);
            if ([ext isEqualToString:@"xlsx"] || [ext isEqualToString:@"xls"] || [ext isEqualToString:@"docx"] || [ext isEqualToString:@"doc"])
            {
                [string replaceOccurrencesOfString:@"file://" withString:@"" options:NSCaseInsensitiveSearch range:NSMakeRange(0, path.length)];
                // 此时获取到文件存储在本地的路径，就可以在自己需要使用的页面使用了
                NSDictionary *dict = @{@"fileName":fileName, @"filePath":objectNull(string), @"extension": objectNull(ext)};
                [[NSNotificationCenter defaultCenter] postNotificationName:@"kFROM_EXTERNAL_REVC_FILE_NOTI" object:nil userInfo:dict];
            }
            
            return YES;
        }
    }
//    BOOL result = [[UMSocialManager defaultManager] handleOpenURL:url];
//    if (!result)
//    {
//        // 其他如支付等SDK的回调
//    }
    return YES;
}

// 当文件名为中文时，解决url编码问题
- (NSString *)URLDecodedString:(NSString *)str
{
    NSString *decodedString=(__bridge_transfer NSString *)CFURLCreateStringByReplacingPercentEscapesUsingEncoding(NULL, (__bridge CFStringRef)str, CFSTR(""), CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding));
    return decodedString;
}

- (NSString *)getUUID
{
    NSString *uuid = [TYZKeychain load:@"com.lingxiao.formeditor"];
    debugLog(@"uuid从缓存读取=%@", uuid);
    if (!uuid) {
        debugLog(@"uuid 是新生成的");
        uuid = [NSString stringWithUUID];
        [TYZKeychain save:@"com.lingxiao.formeditor" data:objectNull(uuid)];
    }
    return uuid;
}


#pragma mark - 用户登录 退出登录 调用
/**
 保存用户信息
 
 @param userInfo 用户信息
 */
- (void)saveUserInfo:(ZHCustomUserInfoModel *)userInfo
{
//    if (self.userInfoModel && self.userInfoModel.loginState == 1 && ![objectNull(self.userInfoModel.appToken) isEqualToString:@""]) { // 登录中
//        userInfo.deviceId = self.userInfoModel.deviceId;
//        userInfo.appToken = self.userInfoModel.appToken;
//        userInfo.userId = self.userInfoModel.userId;
//    }
    self.userInfoModel = userInfo;
    [TYZKeychain save:kUserInfo data:userInfo];
}

/**
 获取用户信息
 
 @return return value description
 */
- (ZHCustomUserInfoModel *)getUserInfo
{
    return [TYZKeychain load:kUserInfo];
}

/**
 删除用户信息
 */
- (void)removeUserInfo
{
    [TYZKeychain remove:kUserInfo];
    self.userInfoModel = nil;
}

/// 登录成功
- (void)loginSuccess {
    
}

/**
 用户退出登录成功
 */
- (void)loginOutSuccess
{
    self.userInfoModel.loginState = 0;
    [self removeUserInfo];
}

/// 用户菜单权限WDAppUserRoutesRequest
/// - Parameter completion: completion description
- (void)requestWithUserRoutes:(RequestCompletionBlock)completion {
    if (!self.userInfoModel) {
        return;
    }
    @weakify(self);
    WDAppUserRoutesRequest *request = [[WDAppUserRoutesRequest alloc] initWithUserId:self.userInfoModel.userId];
    [request startWithCompletionBlockWithSuccess:^(__kindof TYZBaseRequest * _Nonnull request) {
        @strongify(self);
        EDSRespondDataEntity *respond = request.responseModelObject;
        if (respond.code == EDS_NETWORK_SUCCESS) {
            self.userRoutes = respond.data == nil ? @[] : respond.data;
            [EDSUtility writeCacheDataLocalKey:kCacheUserRoutesData saveFilename:kCacheUserRoutesFileName saveid:self.userRoutes];
        } else {
            self.userInfoModel.loginState = 0;
            self.userInfoModel.appToken = @"";
            [self saveUserInfo:self.userInfoModel];
        }
        if (completion) {
            completion(request.responseModelObject);
        }
    } failure:^(__kindof TYZBaseRequest * _Nonnull request) {
        self.userInfoModel.loginState = 0;
        self.userInfoModel.appToken = @"";
        [self saveUserInfo:self.userInfoModel];
        if (completion) {
            completion(request.responseModelObject);
        }
    }];
}

/// 获取用户信息
/// - Parameter completion: completion description
- (void)requestWithUserInfo:(RequestCompletionBlock)completion {
    @weakify(self);
    WDUserDetailRequest *request = [[WDUserDetailRequest alloc] initWithUserId:self.userInfoModel.userId];
    [request startWithCompletionBlockWithSuccess:^(__kindof TYZBaseRequest * _Nonnull request) {
        @strongify(self);
        EDSRespondDataEntity *respond = request.responseModelObject;
        if (respond.code == EDS_NETWORK_SUCCESS) {
            ZHCustomUserInfoModel *userInfo = respond.data;
            userInfo.deviceId = self.userInfoModel.deviceId;
            userInfo.appToken = self.userInfoModel.appToken;
            userInfo.userId = self.userInfoModel.userId;
            userInfo.loginState = self.userInfoModel.loginState;
            [self saveUserInfo:userInfo];
            
            // 获取参数
            [self requestWithTaskParameters];
            
            if (self.userRoutes && self.userRoutes.count > 0) {
                [self requestWithUserRoutes:nil];
            }
            
        }
        if (completion) {
            completion(request.responseModelObject);
        }
    } failure:^(__kindof TYZBaseRequest * _Nonnull request) {
        if (completion) {
            completion(request.responseModelObject);
        }
    }];
}

/// 报警规则
- (void)requestWithAlarmRule {
    if (self.alarmRuleOneModel && self.alarmRuleTwoModel) {
        return;
    }
    @weakify(self);
    WDTaskAlarmRuleRequest *req = [[WDTaskAlarmRuleRequest alloc] initWithType:0];
    [req startWithCompletionBlockWithSuccess:^(__kindof TYZBaseRequest * _Nonnull request) {
        @strongify(self);
        EDSRespondDataEntity *respond = request.responseModelObject;
        if (respond.code == EDS_NETWORK_SUCCESS) {
            self.alarmRuleOneModel = respond.data;
        }
    } failure:^(__kindof TYZBaseRequest * _Nonnull request) {
//        @strongify(self);
//        debugLog(@"失败");
    }];
    
    WDTaskAlarmRuleRequest *request = [[WDTaskAlarmRuleRequest alloc] initWithType:1];
    [request startWithCompletionBlockWithSuccess:^(__kindof TYZBaseRequest * _Nonnull request) {
        @strongify(self);
        EDSRespondDataEntity *respond = request.responseModelObject;
        if (respond.code == EDS_NETWORK_SUCCESS) {
            self.alarmRuleTwoModel = respond.data;
        }
    } failure:^(__kindof TYZBaseRequest * _Nonnull request) {
//        @strongify(self);
//        debugLog(@"失败");
    }];
}

/// 获取参数
- (void)requestWithTaskParameters {
    if (self.userInfoModel == nil || self.userInfoModel.stationId <= 0) {
        return;
    }
    if (self.taskParametersModel) {
        return;
    }
    @weakify(self);
    WDStationTaskParametersRequest *request = [[WDStationTaskParametersRequest alloc] initWithStationId:self.userInfoModel.stationId];
    [request startWithCompletionBlockWithSuccess:^(__kindof TYZBaseRequest * _Nonnull request) {
        @strongify(self);
        EDSRespondDataEntity *respond = request.responseModelObject;
        if (respond.code == EDS_NETWORK_SUCCESS) {
            WDStationTaskParametersModel *model = respond.data;
            if (model.serviceStation.radius == 0) {
                model.serviceStation.radius = 2; // 默认2000米
            }
            if (model.servRefreshTime == 0) {
                model.servRefreshTime = 30;//定时器间隔时间 默认 30秒
            } else {
                model.servRefreshTime = model.servRefreshTime * 60; // 秒
            }
            for (WDTaskAlarmRuleModel *ent in model.alarmRuleList) {
                if ([ent.code isEqualToString:@"0_6"]) { // 超时未发出预警
                    self.alarmRuleOneModel = ent;
                } else if ([ent.code isEqualToString:@"0_9"]) { // 外出距离异常预警
                    self.alarmRuleTwoModel = ent;
                }
            }
            self.taskParametersModel = model;
            [self requestWithOnGoing];
//            debugLog(@"dddd");
        }
    } failure:^(__kindof TYZBaseRequest * _Nonnull request) {
        debugLog(@"失败");
    }];
}

/// 进行中工单列表
- (void)requestWithOnGoing {
    if (self.taskParametersModel.servRefreshTime == 0) {
        return;
    }
    debugLog(@"======%@", [[NSDate date] stringWithFormat:@"yyyy-MM-dd HH:mm:ss"]);
    @weakify(self);
    WDOnGoingListReqModel *reqModel = [WDOnGoingListReqModel new];
    reqModel.engineerId = @(self.userInfoModel.id);
    reqModel.stationId = @(self.userInfoModel.stationId);
    WDOnGoingListRequest *request = [[WDOnGoingListRequest alloc] initWithModel:reqModel];
    [request startWithCompletionBlockWithSuccess:^(__kindof TYZBaseRequest * _Nonnull request) {
        @strongify(self);
        EDSRespondDataEntity *respond = request.responseModelObject;
        if (respond.code == EDS_NETWORK_SUCCESS) {
            NSArray *list = respond.data;
            [self praseWithOnGoingData:list];
        }
    } failure:^(__kindof TYZBaseRequest * _Nonnull request) {
        
    }];
    [self performSelector:@selector(requestWithOnGoing) afterDelay:self.taskParametersModel.servRefreshTime];
}

/// 解析
/// - Parameter list: list description
- (void)praseWithOnGoingData:(NSArray<WDOnGoingListModel *> *)list {
    if (!list || list.count == 0) {
        return;
    }
    
    // 待接车： 并且判断下三十分钟内有没有出服务站或者距离服务站太远 达到条件上报报警信息
    // 检查中和维修中状态 只需判断是否出服务站和是否距离服务站太远 如果达到条件 就上报报警信息
    
    // 服务流程 0.待分派 1.待接车 2.检查中 3.维修中 4.待报单 5.已完成 6.已关闭
    for (WDOnGoingListModel *model in list) {
        if (model.servFlow == 1) { // 待接车
            [self alarmWaitingVeh:model];
        } else if (model.servFlow == 2 || model.servFlow == 3) { // 检查中 || 维修中
            [self alarmInspectionOrMaintenance:model];
        }
    }
}

/// 待接车状态
- (void)alarmWaitingVeh:(WDOnGoingListModel *)model {
    // 待接车： 并且判断下三十分钟内有没有出服务站或者距离服务站太远 达到条件上报报警信息
    NSString *asignTime = model.asignTime; // 抢单时间
    NSString *currDateTime = [[NSDate date] stringWithFormat:@"yyyy-MM-dd HH:mm:ss"]; // 当前时间
    WDTaskAlarmRuleModel *ruleModel = self.alarmRuleOneModel;
    debugLog(@"待接车--抢单时间=%@; 当前时间=%@", asignTime, currDateTime);
    // 计算时间差
    NSInteger minutes = [NSDate minutesWithDateStringDiffer:asignTime endDate:currDateTime format:@"yyyy-MM-dd HH:mm:ss"];
    debugLog(@"时间差=%ld", minutes);
    NSInteger radius = self.taskParametersModel.serviceStation.radius; // 半径(单位：米)
    
    AMapGeoPoint *startPoint = [AMapGeoPoint locationWithLatitude:self.taskParametersModel.serviceStation.latitude longitude:self.taskParametersModel.serviceStation.longitude]; // 服务站经纬度
    CLLocationCoordinate2D coord = [WDLocationManager shareInstance].lastLocation.coordinate;
    AMapGeoPoint *endPoint = [AMapGeoPoint locationWithLatitude:coord.latitude longitude:coord.longitude];
    [[WDLocationManager shareInstance] getTwoPointDistance:startPoint end:endPoint completion:^(NSInteger distance) {
            // 单位:米
        // 三十分钟内有没有出服务站 || 距离服务站太远
        if ((minutes < ruleModel.value && distance < radius)) {
            WDSaveTaskAlarmReqModel *reqModel = [WDSaveTaskAlarmReqModel new];
            reqModel.alarmContent = ruleModel.msg;
            reqModel.alarmLatitude = coord.latitude;
            reqModel.alarmLongitude = coord.longitude;
            reqModel.alarmTime = currDateTime;
            reqModel.engineerId = @(self.userInfoModel.id);
            reqModel.ruleCode = ruleModel.code;
            reqModel.taskId = model.id;
            [self requestWithSaveAlarm:reqModel];
        }
        
        // 距离服务站太远
        if (distance > self.alarmRuleTwoModel.value * 1000) {
            WDSaveTaskAlarmReqModel *reqModel = [WDSaveTaskAlarmReqModel new];
            reqModel.alarmContent = self.alarmRuleTwoModel.msg;
            reqModel.alarmLatitude = coord.latitude;
            reqModel.alarmLongitude = coord.longitude;
            reqModel.alarmTime = currDateTime;
            reqModel.engineerId = @(self.userInfoModel.id);
            reqModel.ruleCode = self.alarmRuleTwoModel.code;
            reqModel.taskId = model.id;
            [self requestWithSaveAlarm:reqModel];
        }
    }];
//    WDSaveTaskAlarmReqModel *m;
    // WDLocationManager
    
    
    debugLog(@"");
}

/// 检查中 || 维修中
- (void)alarmInspectionOrMaintenance:(WDOnGoingListModel *)model {
    // 检查中和维修中状态 只需判断是否出服务站和是否距离服务站太远 如果达到条件 就上报报警信息
    debugLog(@"检查中 || 维修中");
    NSString *currDateTime = [[NSDate date] stringWithFormat:@"yyyy-MM-dd HH:mm:ss"]; // 当前时间
    NSInteger radius = self.taskParametersModel.serviceStation.radius; // 半径(单位：米)
    
    AMapGeoPoint *startPoint = [AMapGeoPoint locationWithLatitude:self.taskParametersModel.serviceStation.latitude longitude:self.taskParametersModel.serviceStation.longitude]; // 服务站经纬度
    CLLocationCoordinate2D coord = [WDLocationManager shareInstance].lastLocation.coordinate;
    AMapGeoPoint *endPoint = [AMapGeoPoint locationWithLatitude:coord.latitude longitude:coord.longitude];
    [[WDLocationManager shareInstance] getTwoPointDistance:startPoint end:endPoint completion:^(NSInteger distance) {
            // 单位:米
        // 距离服务站太远
        if (distance > self.alarmRuleTwoModel.value * 1000) {
            WDSaveTaskAlarmReqModel *reqModel = [WDSaveTaskAlarmReqModel new];
            reqModel.alarmContent = self.alarmRuleTwoModel.msg;
            reqModel.alarmLatitude = coord.latitude;
            reqModel.alarmLongitude = coord.longitude;
            reqModel.alarmTime = currDateTime;
            reqModel.engineerId = @(self.userInfoModel.id);
            reqModel.ruleCode = self.alarmRuleTwoModel.code;
            reqModel.taskId = model.id;
            [self requestWithSaveAlarm:reqModel];
        }
    }];
    
}

/// 将报警信息发送到服务端
/// - Parameter model: model description
- (void)requestWithSaveAlarm:(WDSaveTaskAlarmReqModel *)model {
//    @weakify(self);
    WDSaveTaskAlarmRequest *request = [[WDSaveTaskAlarmRequest alloc] initWithModel:model];
    [request startWithCompletionBlockWithSuccess:^(__kindof TYZBaseRequest * _Nonnull request) {
//        @strongify(self);
        EDSRespondDataEntity *respond = request.responseModelObject;
        if (respond.code == EDS_NETWORK_SUCCESS) {
            WDSaveTaskAlarmModel *resModel = respond.data;
            debugLog(@"提交报警成功!");
        } else {
            debugLog(@"提交报警失败!");
        }
    } failure:^(__kindof TYZBaseRequest * _Nonnull request) {
        debugLog(@"提交报警失败!");
    }];
}
// WDSaveTaskAlarmRequest

/// 判断是否有权限
/// - Parameter code: code description
- (BOOL)hasPermission:(NSNumber *)code parentCode:(NSNumber *)parentCode {
    BOOL has = NO;
    
    if (parentCode) {
        for (int i=0; i<self.userRoutes.count; i++) {
            WDAppUserRoutesModel *model = self.userRoutes[i];
            if (model.code == [parentCode integerValue]) {
                for (int j=0; j<model.children.count; j++) {
                    WDAppUserRoutesModel *ent = model.children[j];
                    if (ent.code == [code integerValue]) {
                        has = YES;
                        break;
                    }
                }
            }
        }
    } else {
        for (int i=0; i<self.userRoutes.count; i++) {
            WDAppUserRoutesModel *model = self.userRoutes[i];
            if (model.code == [code integerValue]) {
                has = YES;
                break;
            } else {
                if (!model.children || model.children.count == 0) {
                    continue;
                }
                for (int j=0; j<model.children.count; j++) {
                    WDAppUserRoutesModel *ent = model.children[j];
                    if (ent.code == [code integerValue]) {
                        has = YES;
                        break;
                    }
                }
            }
        }
    }
    
    return has;
}

/// 是否有到站服务
- (BOOL)hasArrivalService {
    BOOL has = NO;
    // @[@"待接车", @"检查中", @"维修中", @"待报单"]
    NSArray *contains = @[@(100101), @(100102), @(100103), @(100104)];
    for (int i=0; i<self.userRoutes.count; i++) {
        WDAppUserRoutesModel *model = self.userRoutes[i];
        if ([contains containsObject:@(model.code)]) {
            has = YES;
            break;
        }
    }
    return has;
}

/// 是否有外出救援
- (BOOL)hasOutRescue {
    BOOL has = NO;
    NSArray *contains = @[@(100201), @(100202), @(100203), @(100204), @(100205)];
    for (int i=0; i<self.userRoutes.count; i++) {
        WDAppUserRoutesModel *model = self.userRoutes[i];
        if ([contains containsObject:@(model.code)]) {
            has = YES;
            break;
        }
    }
    return has;
}

/// 是否有工单搜索
- (BOOL)hasWorkOrder {
    BOOL has = NO;
    NSArray *contains = @[@(100301)];
    for (int i=0; i<self.userRoutes.count; i++) {
        WDAppUserRoutesModel *model = self.userRoutes[i];
        if ([contains containsObject:@(model.code)]) {
            has = YES;
            break;
        }
    }
    return has;
}

/// 是否有我的
- (BOOL)hasMine {
    BOOL has = NO;
    NSArray *contains = @[@(100302)];
    for (int i=0; i<self.userRoutes.count; i++) {
        WDAppUserRoutesModel *model = self.userRoutes[i];
        if ([contains containsObject:@(model.code)]) {
            has = YES;
            break;
        }
    }
    return has;
}

/// 是否有扫码
- (BOOL)hasScanCode {
    BOOL has = NO;
    NSArray *contains = @[@(100303)];
    for (int i=0; i<self.userRoutes.count; i++) {
        WDAppUserRoutesModel *model = self.userRoutes[i];
        if ([contains containsObject:@(model.code)]) {
            has = YES;
            break;
        }
    }
    return has;
}

#pragma mark - UITabBarControllerDelegate
- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController
{
    self.TabSelectedIndex = tabBarController.selectedIndex;
    TYZBaseViewController *vc = tabBarController.selectedViewController;
    NSDate *date = [[NSDate alloc] init];
    if ([vc isEqual:viewController])
    {
        // 处理双击事件
        if (date.timeIntervalSince1970 - _lastDate.timeIntervalSince1970 < 0.5)
        {
            debugLog(@"双击事件");
        }
        _lastDate = date;
    }
    
    debugLog(@"TabSelectedIndex=%zd", self.TabSelectedIndex);
    
}

- (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController
{
//    debugLog(@"dddddddd");
    return YES;
}

/// 拉取微信客服
- (void)openWXCustomerService
{
    if (![WXApi isWXAppInstalled])
    {
        [SVProgressHUD showInfoWithStatus:@"您需要安装微信APP"];
        return;
    }
    WXOpenCustomerServiceReq *req = [[WXOpenCustomerServiceReq alloc] init];
    req.corpid = kWEIXIN_CORP_ID; // 企业id
    req.url = kWEIXIN_CUSTOMER_SERVICE; // 客服url
    [WXApi sendReq:req completion:nil];
}

#pragma mark - WXApiDelegate
- (void)onReq:(BaseReq *)req
{
    debugLog(@"tool收到一个来自微信的请求");
    
}
- (void)onResp:(BaseResp *)resp
{
    debugLog(@"返回的=%@", NSStringFromClass([resp class]));
    if ([resp isKindOfClass:[WXOpenCustomerServiceResp class]])
    {
        int errCode = resp.errCode;
        NSString *string = resp.errStr;
//        NSString *log = [NSString stringWithFormat:@"Resp:errCode=%d; erroMsg=%@", errCode, string];
//        [[TYZLogManager sharedInstance] logInfo:@"" logStr:log, nil];
        debugLog(@"errCode=%d; errStr=%@", errCode, string);
    } else if ([resp isKindOfClass:[SendAuthResp class]]) {
        SendAuthResp *sender = (SendAuthResp *)resp;
        int errCode = resp.errCode;
        NSString *errStr = resp.errStr;
        debugLog(@"微信登录授权.errCode=%d; errStr=%@", errCode, errStr);
        NSString *code = objectNull(sender.code);
        [[NSNotificationCenter defaultCenter] postNotificationName:kWEIXIN_AUTH_REVC_CODE object:code];
    } else if ([resp isKindOfClass:[SendMessageToWXResp class]]) {
        SendMessageToWXResp *sender = (SendMessageToWXResp *)resp;
        debugLog(@"errorcode=%d; erromsg=%@", sender.errCode, sender.errStr);
    }
}


#pragma mark - AMapLocationManagerDelegate
- (void)amapLocationManager:(AMapLocationManager *)manager doRequireLocationAuth:(CLLocationManager *)locationManager
{
    @weakify(self);
    [locationManager requestAlwaysAuthorization];
    static dispatch_once_t onceToken; //2.声明一个静态的gcd的单次任务
   dispatch_once(&onceToken, ^{ //3.执行gcd单次任务：对对象进行初始化
       [self.locationManager requestLocationWithReGeocode:YES completionBlock:^(CLLocation *location, AMapLocationReGeocode *regeocode, NSError *error) {
           @strongify(self);
           if (error)
           {
               if (error.code == AMapLocationErrorLocateFailed)
               {
//                   self.city = @"合肥市";
//                   self.latitude = 31.86694;
//                   self.longitude = 117.2827;
                   return;
               }
           }
           if (regeocode) {
               self.city = regeocode.city;
               self.address = [NSString stringWithFormat:@"%@%@",regeocode.province,regeocode.city];
               self.latitude = location.coordinate.latitude;
               self.longitude = location.coordinate.longitude;
           } else {
//               self.city = @"合肥市";
//               self.latitude = 31.86694;
//               self.longitude = 117.2827;
           }
       }];
   });
}

@end

























